<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://erdangjiade.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: xiaojie <997031758@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 后台文章管理
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\Article;
use app\admin\model\Category;
use app\common\controller\AdminBase;
use think\Request;

class Pages extends AdminBase
{
    public function index(Request $request)
    {
        if($request->isAjax()){
            $bulider = Article::order(['sort','id'=>'desc'])
                ->where('type','page')
                ->page($request->get('page'),$request->get('limit'));

            return $this->layuiTableJson($bulider->count(),$bulider->select());
        }
        return view();
    }

    public function apiGetCategory(Request $request, Category $category)
    {
        if($request->isAjax()){
            $categories = $category
                ->field('id,title,parent_id,is_directory')
                ->order('sort')
                ->where('parent_id',$request->get('parent_id/d'))
                ->where('type','page')
                ->select()->toArray();

            return $this->success('数据获取成功','',$categories);
        }
    }

    public function create()
    {
        return view();
    }

    public function save(Request $request, Article $article)
    {
        $article->data($request->only(['category_id','title','description','content','thumb_image','images','status','sort','hits']));
        $article->type = 'page';
        $article->save();

        return $this->success('添加成功','index');
    }

    public function edit(Request $request)
    {
        $article = Article::find($request->get('id'));
        $category = Category::find($article->category_id);

        return view('edit',[
            'article' => $article,
            'chooseData' => json_encode(explode('-',trim($category->path.$category->id,'-')))
        ]);
    }

    public function update(Request $request)
    {
        $article = Article::find($request->post('id/d'));
        $article->save($request->only(['category_id','title','description','content','thumb_image','images','status','sort','hits']));
        return $this->success('保存成功','index');
    }

    public function delete(Request $request)
    {
        Article::destroy($request->get('id'));

        return $this->success('操作成功','index');
    }
    
}
